package com.demo.controller;

import com.demo.utils.UserCacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.demo.pojo.User;

import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/app")
public class CacheController {
    private static final Logger logger = LoggerFactory.getLogger(CacheController.class);
    @PostMapping(path = "/user",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public User insertUserInfo(@RequestBody User user, BindingResult bindingResult) throws ExecutionException {
        logger.info("缓存请求参数：{}",user.toString());
        User usercache=UserCacheUtil.getUserFromCache(user.getUserid());
        if(null==usercache){
            UserCacheUtil.insertCache(user);
        }
        logger.info("缓存信息：{}",usercache.toString());
        if(user.getUsername().equals(usercache.getUsername())){
            logger.info("缓存中已有，无需缓存");
        }else{
            UserCacheUtil.insertCache(user);
        }
        return user;
    }

    @PostMapping(path = "/user1",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public User insertUserInfo1(@RequestBody User user, BindingResult bindingResult) throws ExecutionException {
        logger.info("缓存请求参数：{}",user.toString());
        User usercache=UserCacheUtil.getUserFromCache1(user.getUserid());
        if(null==usercache){
            UserCacheUtil.insertCache1(user);
        }
        logger.info("缓存信息：{}",usercache.toString());
        if(user.getUsername().equals(usercache.getUsername())){
            logger.info("缓存中已有，无需缓存");
        }else{
            UserCacheUtil.insertCache1(user);
        }
        return user;
    }

    @GetMapping(path = "/user/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public User getUser(@PathVariable("id") int id) throws ExecutionException {
        logger.info("缓存请求参数：{}",id);
        User usercache=UserCacheUtil.getUserFromCache(id);
        if(null==usercache){
            logger.info("无效的Id");
            return  null;
        }else{
            logger.info("缓存信息：{}",usercache.toString());
            return usercache;
        }
    }
    @GetMapping(path = "/user1/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public User getUser1(@PathVariable("id") int id) throws ExecutionException {
        logger.info("缓存请求参数：{}",id);
        User usercache=UserCacheUtil.getUserFromCache1(id);
        if(null==usercache){
            logger.info("无效的Id");
            return  null;
        }else{
            logger.info("缓存信息：{}",usercache.toString());
            return usercache;
        }
    }
}
